#include <cstdio>
#include <cstring>
#include <algorithm>

const int N = 3000 + 7;
const int E = 30000 + 7;
const int S = 10000 + 7;

int head[N], nxt[E], to[E], tot;
int val[N], ival[N], (*opt[N]) (int, int), du[N];
int q[N], fr, ba;
char s[40];
int n, m;
int sans[S][N];

int NOT(int x, int y) {return !y;}
int AND(int x, int y) {return x & y;}
int OR(int x, int y) {return x | y;}
int XOR(int x, int y) {return x ^ y;}
int NAND(int x, int y) {return !((!x) & y);}
int NOR(int x, int y) {return !((!x) | y);}

int init() {
    tot = 0;
    memset(du, 0, sizeof du);
    memset(to, 0, sizeof to);
    memset(nxt, 0, sizeof nxt);
    memset(head, 0, sizeof head);
}

int add(int x, int y) {
    nxt[++tot] = head[x], head[x] = tot, to[tot] = y;
}

int main() {
	
    int cases, x, y, z, st, ss;
    scanf("%d", &cases);
	
    while(cases--) {
	init();
	scanf("%d%d", &m, &n);
	for(int i = 1; i <= n; ++i) {
	    scanf("%s%d", s, &x); du[i] = x;
	    if(s[0] == 'A') opt[i] = AND, ival[i] = 1;
	    else if(s[0] == 'O') opt[i] = OR, ival[i] = 0;
	    else if(s[0] == 'X') opt[i] = XOR, ival[i] = 0;
	    else if(s[1] == 'A') opt[i] = NAND, ival[i] = 0;
	    else if(s[2] == 'T') opt[i] = NOT, ival[i] = -1;
	    else opt[i] = NOR, ival[i] = 1;
	    for(int j = 1; j <= x; ++j) {
		scanf("%*c%c%d", &s[0], &y);
		if(s[0] == 'I') add(y + n, i);
		else add(y, i);
	    }
	}
		
	fr = ba = 1;
	for(int i = n + 1; i <= n + m; ++i) 
	    q[ba++] = i;
	for(int i = 1; i <= n; ++i) if(!du[i]) q[ba++] = i;
	while(fr != ba) {
	    x = q[fr++];
	    for(int i = head[x]; i; i = nxt[i])
		if(!--du[to[i]])
		    q[ba++] = to[i];
	}
		
	if(ba <= n + m) {
	    puts("LOOP"); 
	    scanf("%d", &st);
	    for(int i = 1; i <= st; ++i)
		for(int j = 1; j <= m; ++j)
		    scanf("%*d");
	    for(int i = 1; i <= st; ++i) {
		scanf("%d", &ss);
		for(int i = 1; i <= ss; ++i)
		    scanf("%*d");
	    }
	    continue;
	}
		
	scanf("%d", &st);
	for(int u = 1; u <= st; ++u) {
	    for(int i = n + 1; i <= n + m; ++i)
		scanf("%d", &val[i]);
	    for(int i = 1; i <= n; ++i) 
		val[i] = ival[i];
	    for(int i = 1; i <= n + m; ++i) {
		x = q[i];
		for(int j = head[x]; j; j = nxt[j])
		    val[to[j]] = opt[to[j]](val[to[j]], val[x]);
	    }
	    for(int i = 1; i <= n + m; ++i)
		sans[u][i] = val[i];
	}
		
	for(int u = 1; u <= st; ++u) {
	    scanf("%d", &ss);
	    for(int i = 1; i <= ss; ++i) {
		scanf("%d", &x);
		printf("%d ", sans[u][x]);
	    }
	    putchar(10);
	}
    }
	
    return 0;

}